<template>

    
  <div class="content with-diagram" id="js-drop-zone">

    <div class="message intro">
      <div class="note">
        Drop BPMN diagram from your desktop or <a id="js-create-diagram" href>create a new diagram</a> to get started.
        <br>
        或者打开文件 <a style="margin:10px;" v-for="file in files" @click="openFile(file)" :key="file" href="javascript:;">{{file}}</a>
      </div>
    </div>

    <div class="message error">
      <div class="note">
        <p>Ooops, we could not display the BPMN 2.0 diagram.</p>

        <div class="details">
          <span>Import Error Details</span>
          <pre></pre>
        </div>
      </div>
    </div>

    <div class="canvas" id="js-canvas"></div>
    <div class="properties-panel-parent" id="js-properties-panel"></div>

    <ul class="buttons">
    <li>
      download
    </li>
    <li>
      <a id="js-download-diagram" href title="download BPMN diagram">
        BPMN diagram
      </a>
    </li>
    <li>
      <a id="js-download-svg" href title="download as SVG image">
        SVG image
      </a>
    </li>
    <li>
      <a @click="save" href="javascript:;" title="download as SVG image" class="active">保存文件</a>
    </li>

    <li>
      <input type="text" style="width:300px;" v-model="fileName"/>
    </li>
  </ul>

  </div>


</template>


<script>
import "bpmn-js-properties-panel/styles/properties.less";
import "bpmn-js/dist/assets/bpmn-font/css/bpmn.css";
import "bpmn-js/dist/assets/diagram-js.css";

import $ from "jquery";
import BpmnModeler from "bpmn-js/lib/Modeler";

import propertiesPanelModule from "bpmn-js-properties-panel";
import propertiesProviderModule from "bpmn-js-properties-panel/lib/provider/camunda";
import camundaModdleDescriptor from "camunda-bpmn-moddle/resources/camunda";

import { debounce } from "min-dash";

import diagramXML from "../../resources/newDiagram.bpmn";
import {getNode} from "../util/bpmnUtil";
import propProvider from "../util/prop-panel";
import cjcPropertiesProvider from "../util/cjc";

import signavioCompat from "bpmn-js-signavio-compat";
import jsSketchy from "bpmn-js-sketchy";
// import nyan from "bpmn-js-nyan";

import resizeAllModule from 'bpmn-js-nyan/lib/resize-all-rules';
import colorPickerModule from 'bpmn-js-nyan/lib/color-picker';
import nyanDrawModule from 'bpmn-js-nyan/lib/nyan/draw';
import nyanPaletteModule from 'bpmn-js-nyan/lib/nyan/palette';

var bpmnModeler;


console.log(propertiesPanelModule);


const exec = function() {
  var container = $("#js-drop-zone");

  var canvas = $("#js-canvas");

  bpmnModeler = new BpmnModeler({
    container: canvas,
    propertiesPanel: {
      parent: "#js-properties-panel"
    },
    additionalModules: [propertiesPanelModule, propertiesProviderModule,propProvider,signavioCompat,
    resizeAllModule,
    colorPickerModule,
    nyanDrawModule,
    nyanPaletteModule
    ],
    // additionalModules: [propertiesPanelModule, propertiesProviderModule,propProvider,cjcPropertiesProvider],
    moddleExtensions: {
      camunda: camundaModdleDescriptor
    }
  });
  container.removeClass("with-diagram");

  // bpmnModeler.on("selection.changed", selection => {
  //   // console.log(selection);
  //   const { newSelection , oldSelection } = selection;
  //
  //   if(newSelection){
  //
  //     for(const sel of newSelection){
  //
  //
  //       var node = getNode(sel);
  //
  //       console.log(node);
  //
  //     }
  //
  //   }
  //
  //   // const shap = newSelection[0];
  //   //
  //   // console.log(shap.bussinessObject);
  //
  // });

  function createNewDiagram() {
    openDiagram(diagramXML);
  }

  window.openDiagram = function(xml) {
    bpmnModeler.importXML(xml, function(err) {
      if (err) {
        container.removeClass("with-diagram").addClass("with-error");

        container.find(".error pre").text(err.message);

        console.error(err);
      } else {
        container.removeClass("with-error").addClass("with-diagram");
        bpmnModeler.get("canvas").zoom("fit-viewport");
      }
    });
  };

  function saveSVG(done) {
    bpmnModeler.saveSVG(done);
  }

  function saveDiagram(done) {
    bpmnModeler.saveXML({ format: true }, function(err, xml) {
      done(err, xml);
    });
  }

  function registerFileDrop(container, callback) {
    function handleFileSelect(e) {
      e.stopPropagation();
      e.preventDefault();

      var files = e.dataTransfer.files;

      var file = files[0];

      var reader = new FileReader();

      reader.onload = function(e) {
        var xml = e.target.result;

        callback(xml);
      };

      reader.readAsText(file);
    }

    function handleDragOver(e) {
      e.stopPropagation();
      e.preventDefault();

      e.dataTransfer.dropEffect = "copy"; // Explicitly show this is a copy.
    }

    container.get(0).addEventListener("dragover", handleDragOver, false);
    container.get(0).addEventListener("drop", handleFileSelect, false);
  }

  ////// file drag / drop ///////////////////////

  // check file api availability
  if (!window.FileList || !window.FileReader) {
    window.alert(
      "Looks like you use an older browser that does not support drag and drop. " +
        "Try using Chrome, Firefox or the Internet Explorer > 10."
    );
  } else {
    registerFileDrop(container, openDiagram);
  }

  // bootstrap diagram functions

  $("#js-create-diagram").click(function(e) {
    e.stopPropagation();
    e.preventDefault();

    createNewDiagram();
  });

  var downloadLink = $("#js-download-diagram");
  var downloadSvgLink = $("#js-download-svg");

  $(".buttons a").click(function(e) {
    if (!$(this).is(".active")) {
      e.preventDefault();
      e.stopPropagation();
    }
  });

  function setEncoded(link, name, data) {
    var encodedData = encodeURIComponent(data);

    if (data) {
      link.addClass("active").attr({
        href: "data:application/bpmn20-xml;charset=UTF-8," + encodedData,
        download: name
      });
    } else {
      link.removeClass("active");
    }
  }

  var exportArtifacts = debounce(function() {
    saveSVG(function(err, svg) {
      setEncoded(downloadSvgLink, "diagram.svg", err ? null : svg);
    });

    saveDiagram(function(err, xml) {
      setEncoded(downloadLink, "diagram.bpmn", err ? null : xml);
    });
  }, 500);

  bpmnModeler.on("commandStack.changed", exportArtifacts);
};

export default {
  data() {
    return {
      files: [],
      fileName: null
    };
  },

  mounted() {
    this.$nextTick(exec);
    this.$axios.get("/api/file/list").then(({ data }) => {
      this.files = data;
    });
  },

  methods: {
    openFile(file) {
      this.fileName = file;
      this.$axios
        .get("/api/file/get", { params: { name: file } })
        .then(({ data }) => {
          openDiagram(data);
        });
    },

    saveFile(xml, fileName) {
      this.$axios.post("/api/file/save", {
        file: fileName || this.fileName,
        content: xml
      });
    },

    save() {
      const definitions = bpmnModeler.getDefinitions();
      definitions.targetNamespace = "http://www.activiti.org/test";
      const process = definitions.rootElements[0];
      process.isExecutable = true;
      bpmnModeler.saveXML({ format: true }, (err, xml) => {
        if (err) {
          return console.error(err);
        }
        this.saveFile(xml);
      });
    }
  }
};
</script>

<style lang="less">
// @import "bpmn-js-properties-panel/styles/properties";

* {
  box-sizing: border-box;
}

body,
html {
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;

  font-size: 12px;

  height: 100%;
  max-height: 100%;
  padding: 0;
  margin: 0;
}

a:link {
  text-decoration: none;
}

.content {
  position: relative;
  width: 100%;
  height: 100%;

  > .message {
    width: 100%;
    height: 100%;
    text-align: center;
    display: table;

    font-size: 16px;
    color: #111;

    .note {
      vertical-align: middle;
      text-align: center;
      display: table-cell;
    }

    &.error {
      .details {
        max-width: 500px;
        font-size: 12px;
        margin: 20px auto;
        text-align: left;
        color: #bd2828;
      }

      pre {
        border: solid 1px #bd2828;
        background: #fefafa;
        padding: 10px;
        color: #bd2828;
      }
    }
  }
  &:not(.with-error) .error,
  &.with-error .intro,
  &.with-diagram .intro {
    display: none;
  }

  .canvas {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }

  .canvas,
  .properties-panel-parent {
    display: none;
  }

  &.with-diagram {
    .canvas,
    .properties-panel-parent {
      display: block;
    }
  }
}

.buttons {
  position: fixed;
  bottom: 20px;
  left: 20px;

  padding: 0;
  margin: 0;
  list-style: none;

  > li {
    display: inline-block;
    margin-right: 10px;

    > a {
      background: #ddd;
      border: solid 1px #666;
      display: inline-block;
      padding: 5px;
    }
  }

  a {
    opacity: 0.3;
  }

  a.active {
    opacity: 1;
  }
}

.properties-panel-parent {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  width: 260px;
  z-index: 10;
  border-left: 1px solid #ccc;
  overflow: auto;
  &:empty {
    display: none;
  }
  > .djs-properties-panel {
    padding-bottom: 70px;
    min-height: 100%;
  }
}
</style>

